<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-brand">
        <i class="fas fa-mug-hot brand-icon"></i>
        <div class="brand-info">
          <h1 class="brand-name">禅意茶道</h1>
          <p class="brand-slogan">茶叶产品管理系统</p>
        </div>
      </div>
      <nav class="main-nav">
        <ul class="nav-list">
          <li><a href="#" class="nav-link active">茶叶产品</a></li>
        </ul>
      </nav>
    </header>
    
    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 统计信息卡片 -->
      <section class="stats-section">
        <h2 class="section-subtitle">茶叶产品概览</h2>
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-icon-wrapper">
              <i class="fas fa-leaf stat-icon"></i>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.totalProducts }}</div>
              <div class="stat-label">茶叶种类</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon-wrapper">
              <i class="fas fa-box stat-icon"></i>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.totalStock }}</div>
              <div class="stat-label">总库存(g)</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon-wrapper">
              <i class="fas fa-coins stat-icon"></i>
            </div>
            <div class="stat-content">
              <div class="stat-value">¥{{ stats.totalValue }}</div>
              <div class="stat-label">总价值</div>
            </div>
          </div>
        </div>
        
        <!-- 新增数据统计表格 -->
        <div class="data-stats-section">
          <h3 class="stats-table-title">产品库存详情</h3>
          <div class="stats-table-container">
            <table class="stats-table">
              <thead>
                <tr>
                  <th>产品名称</th>
                  <th>库存数量</th>
                  <th>库存占比</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="product in products" :key="product.id">
                  <td>{{ product.name }}</td>
                  <td>{{ product.stock }}</td>
                  <td>
                    {{ calculatePercentage(product.stock) }}%
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </section>
      
      <!-- 茶叶产品管理部分 -->
      <section class="products-section">
        <h2 class="section-title">茶叶产品管理</h2>
        
        <!-- 操作按钮 -->
        <div class="action-bar">
          <button class="btn btn-add" @click="openAddProductModal">添加新茶叶</button>
        </div>
        
        <!-- 产品数据表格 -->
        <div class="data-table-container">
          <table class="data-table">
            <thead>
              <tr>
                <th>产品名称</th>
                <th>描述</th>
                <th>价格 (¥)</th>
                <th>重量 (g)</th>
                <th>库存</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="product in products" :key="product.id">
                <td>{{ product.name }}</td>
                <td>{{ product.description }}</td>
                <td>¥{{ product.price }}</td>
                <td>{{ product.weight }}</td>
                <td>{{ product.stock }}</td>
                <td>
                  <span class="status-badge" :class="product.status">{{ 
                    product.status === 'active' ? '上架' : '下架' 
                  }}</span>
                </td>
                <td class="action-buttons">
                  <button class="btn btn-edit" @click="editProduct(product)">编辑</button>
                  <button class="btn btn-delete" @click="deleteProduct(product.id)">删除</button>
                </td>
              </tr>
              <tr v-if="products.length === 0">
                <td colspan="7" class="no-data">暂无茶叶产品数据</td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>
    </main>
    
    <!-- 通知组件 -->
    <div class="notification" v-if="showNotification" :class="{success: notificationSuccess}">
      <i class="fas" :class="notificationSuccess ? 'fa-check-circle' : 'fa-exclamation-circle'"></i>
      <span>{{ notificationMessage }}</span>
    </div>
    
    <!-- 模态框 - 添加/编辑茶叶产品 -->
    <div v-if="showProductModal" class="modal-overlay">
      <div class="modal">
        <div class="modal-header">
          <h2>{{ isEditing ? '编辑茶叶产品' : '添加新茶叶产品' }}</h2>
          <button class="close-modal" @click="closeProductModal">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="product-name">产品名称</label>
            <input 
              type="text" 
              id="product-name" 
              v-model="currentProduct.name"
              class="form-control"
              required
            >
          </div>
          <div class="form-group">
            <label for="product-description">描述</label>
            <textarea 
              id="product-description" 
              v-model="currentProduct.description"
              class="form-control"
              rows="3"
              required
            ></textarea>
          </div>
          <div class="form-group">
            <label for="product-price">价格 (¥)</label>
            <input 
              type="number" 
              id="product-price" 
              v-model="currentProduct.price"
              class="form-control"
              min="0"
              step="0.01"
              required
            >
          </div>
          <div class="form-group">
            <label for="product-weight">重量 (g)</label>
            <input 
              type="number" 
              id="product-weight" 
              v-model="currentProduct.weight"
              class="form-control"
              min="0"
              required
            >
          </div>
          <div class="form-group">
            <label for="product-stock">库存</label>
            <input 
              type="number" 
              id="product-stock" 
              v-model="currentProduct.stock"
              class="form-control"
              min="0"
              required
            >
          </div>
          <div class="form-group">
            <label for="product-status">状态</label>
            <select 
              id="product-status" 
              v-model="currentProduct.status"
              class="form-control"
              required
            >
              <option value="active">上架</option>
              <option value="inactive">下架</option>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-cancel" @click="closeProductModal">取消</button>
          <button class="btn btn-save" @click="saveProduct">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      // API基础URL
      API_BASE_URL: '/api/chadao',
      
      // 响应式数据
      products: [],
      stats: {
        totalProducts: 0,
        totalStock: 0,
        totalValue: 0
      },
      
      activeTab: 'products',
      showNotification: false,
      notificationMessage: '',
      notificationSuccess: false,
      showProductModal: false,
      currentProduct: {
        id: null,
        name: '',
        description: '',
        price: 0,
        weight: 0,
        stock: 0,
        status: 'active'
      },
      isEditing: false
    };
  },
  
  methods: {
    // 计算单个产品库存占比
    calculatePercentage(stock) {
      if (this.stats.totalStock === 0) return 0;
      return ((stock / this.stats.totalStock) * 100).toFixed(1);
    },
    
    // 显示通知
    showNotificationMessage(message, isSuccess) {
      this.notificationMessage = message;
      this.notificationSuccess = isSuccess;
      this.showNotification = true;
      
      setTimeout(() => {
        this.showNotification = false;
      }, 3000);
    },
    
    // 计算统计数据
    calculateStats() {
      this.stats.totalProducts = this.products.length;
      this.stats.totalStock = this.products.reduce((total, product) => total + product.stock, 0);
      this.stats.totalValue = this.products.reduce((total, product) => total + (product.price * product.stock), 0).toFixed(2);
    },
    
    // 获取所有茶叶产品
    fetchProducts() {
      const vm = this;
      axios.get(`${this.API_BASE_URL}/getproducts`)
        .then(function(response) {
          // 注意这里根据ResultJson的包装结构调整
          vm.products = response.data.data;
          vm.calculateStats();
          
          vm.showNotificationMessage('茶叶产品数据加载成功', true);
        })
        .catch(function(error) {
          console.error('获取茶叶产品数据失败:', error);
          vm.showNotificationMessage('获取茶叶产品数据失败', false);
          
          // 使用默认数据作为后备
          vm.products = [
            { 
              id: 1, 
              name: "龙井绿茶", 
              description: "顶级西湖龙井，清香扑鼻", 
              price: 350, 
              weight: 100, 
              stock: 15, 
              status: "active" 
            },
            { 
              id: 2, 
              name: "普洱熟茶", 
              description: "陈年普洱，茶香醇厚", 
              price: 280, 
              weight: 357, 
              stock: 8, 
              status: "active" 
            }
          ];
          vm.calculateStats();
        });
    },
    
    // 打开添加产品模态框
    openAddProductModal() {
      this.isEditing = false;
      this.currentProduct = {
        id: null,
        name: '',
        description: '',
        price: 0,
        weight: 0,
        stock: 0,
        status: 'active'
      };
      this.showProductModal = true;
    },
    
    // 打开编辑产品模态框
    editProduct(product) {
      this.isEditing = true;
      this.currentProduct = { ...product };
      this.showProductModal = true;
    },
    
    // 关闭产品模态框
    closeProductModal() {
      this.showProductModal = false;
    },
    
    // 保存产品（新增或更新）
    saveProduct() {
      // 表单验证
      if (!this.currentProduct.name || !this.currentProduct.description || 
          this.currentProduct.price <= 0 || this.currentProduct.weight <= 0 || 
          this.currentProduct.stock < 0) {
        this.showNotificationMessage('请填写所有必填字段，且价格、重量和库存必须为正数', false);
        return;
      }
      
      const vm = this;
      if (this.isEditing) {
        // 更新现有产品
        axios.post(`${this.API_BASE_URL}/updateproduct`, this.currentProduct)
          .then(function() {
            vm.showNotificationMessage('茶叶产品信息已更新', true);
          })
          .catch(function(error) {
            console.error('更新茶叶产品失败:', error);
            vm.showNotificationMessage('更新茶叶产品失败', false);
          });
      } else {
        // 创建新产品
        axios.post(`${this.API_BASE_URL}/addproduct`, this.currentProduct)
          .then(function() {
            vm.showNotificationMessage('新茶叶产品已添加', true);
          })
          .catch(function(error) {
            console.error('创建茶叶产品失败:', error);
            vm.showNotificationMessage('创建茶叶产品失败', false);
          });
      }
      
      // 刷新产品列表
      this.fetchProducts();
      this.closeProductModal();
    },
    
    // 删除产品
    deleteProduct(id) {
      if (confirm('确定要删除此茶叶产品吗？')) {
        const vm = this;
        axios.delete(`${this.API_BASE_URL}/deleteproduct/${id}`)
          .then(function() {
            vm.showNotificationMessage('茶叶产品已删除', true);
            // 刷新产品列表
            vm.fetchProducts();
          })
          .catch(function(error) {
            console.error('删除茶叶产品失败:', error);
            vm.showNotificationMessage('删除茶叶产品失败', false);
          });
      }
    }
  },
  
  mounted() {
    this.fetchProducts();
  }
};
</script>

<style>
/* 样式保持不变 */
/* 全局样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

:root {
  --primary-color: #4a6741; /* 深绿色，代表茶 */
  --secondary-color: #789070; /* 中绿色 */
  --accent-color: #d7ccc8; /* 浅米色 */
  --light-color: #f5f5f0; /* 极浅米色 */
  --dark-color: #2e4d32; /* 深绿色 */
  --text-color: #3e2723; /* 深棕色 */
  --background-color: #f9f5f0; /* 浅米色背景 */
  --card-background: #ffffff; /* 卡片白色背景 */
  --border-radius: 16px; /* 更大的圆角 */
  --box-shadow: 0 10px 30px rgba(0, 0, 0, 0.06); /* 柔和阴影 */
  --transition: all 0.3s ease; /* 平滑过渡 */
  --section-padding: 30px; /* 区块内边距 */
}

body {
  font-family: 'Noto Serif SC', 'Source Han Serif SC', serif; /* 更优雅的中文字体 */
  color: var(--text-color);
  background-color: var(--background-color);
  line-height: 1.6;
}

.app-container {
  max-width: 1280px;
  margin: 0 auto;
  padding: 20px;
}

/* 后续样式保持不变... */
</style>